package com.svo.weitu.model;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.text.Html;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.svo.platform.utils.HttpUtil;
import com.svo.platform.utils.SvoUtil;
import com.svo.platform.widget.LoadDialog;
import com.svo.weitu.App;
import com.svo.weitu.util.Cons;
import com.svo.weitu.util.UiUtil;
import com.svo.weitu.util.Utils;

import org.json.JSONObject;

import java.io.File;

import static android.content.Context.DOWNLOAD_SERVICE;

public class MNew {
	private BroadcastReceiver broadcastReceiver;
	Activity activity;
	public MNew(Activity activity){
		this.activity = activity;
	}

	/**
	 * 检查新版本
	 * @param isShowDialog 是否显示等待框
	 */
	public void checkNew(final boolean isShowDialog,BroadcastReceiver broadcastReceiver) {
		this.broadcastReceiver = broadcastReceiver;
		if (isShowDialog) {//设置页面每次都去请求
			reqNet(isShowDialog);
		}else {//首页每隔12小时去请求
			long lastReqUpdateTime = App.context.getSharedPreferences("main",0).getLong("lastReqUpdateTime",0);
			if (System.currentTimeMillis() - lastReqUpdateTime > 12*60*60*1000l){
				reqNet(false);
			}else {
				String json = App.context.getSharedPreferences("main",0).getString("update","");
				check(json,false);
			}
		}
	}

	private void reqNet(final boolean isShowDialog) {
		int version = SvoUtil.getVersion(App.context);
		HttpUtil.get(Cons.gen + "ConfigSevlet?flag=getParam&app=weitu&version=" + version, null,
				new AsyncHttpResponseHandler() {
					LoadDialog loadDialog;
					@Override
					public void onStart() {
						if (isShowDialog) {
							if (loadDialog == null) {
								loadDialog = new LoadDialog(activity);
							}
							loadDialog.show();
						}
					}

					@Override
					public void onSuccess(String json) {
						super.onSuccess(json);
						App.context.getSharedPreferences("main",0).edit().putString("update",json).putLong("lastReqUpdateTime",System.currentTimeMillis()).commit();
						check(json,isShowDialog);
					}

					@Override
					public void onFinish() {
						super.onFinish();
						if (loadDialog != null) {
							loadDialog.dismiss();
						}
					}
				});
	}

	private void check(String json,boolean isShowHint) {
		if (activity == null) {
			return;
		}
		try {
			JSONObject jo = new JSONObject(json);
			int maxv = jo.optInt("maxV",1);
			final String downUrl = jo.optString("downUrl","");
			String hint = jo.optString("hint","");
			int curVersion = Utils.getVersionCode(App.context);
			if (curVersion < maxv) {// 有新版本，但是不用强制更新
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				builder.setTitle("提示");
				builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DownloadManager downloadManager = (DownloadManager)App.context.getSystemService(DOWNLOAD_SERVICE);
						DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
						// 默认的Android系统下载存储目录
						request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "weitu.apk");
						request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
						request.setMimeType("application/vnd.android.package-archive");
						request.setTitle("唯图新版本");
						long Id = downloadManager.enqueue(request);
						UiUtil.toast(App.context,"开始下载...");
						listener(Id);
					}
				});
				builder.setMessage(Html.fromHtml(hint));
				builder.setCancelable(true);
				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				Dialog dialog = builder.create();
				dialog.setCanceledOnTouchOutside(false);
				dialog.show();
			}else {
				if (isShowHint)
					UiUtil.toast(App.context,"已是最新");
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (isShowHint)
				UiUtil.toast(App.context,"已是最新");
		}
	}
	private void listener(final long Id) {
		// 注册广播监听系统的下载完成事件。
		IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
		broadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				if (ID == Id) {
					try {
						UiUtil.toast(context,"下载完成");
						Intent i = new Intent(Intent.ACTION_VIEW);
						File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"weitu.apk");
						i.setDataAndType(Uri.parse("file://"+file.getAbsolutePath()), "application/vnd.android.package-archive");
						activity.startActivity(i);
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			}
		};
		activity.registerReceiver(broadcastReceiver, intentFilter);
	}
}
